import logging
import random
from . import db
from .new_models import (
    CareElderDemand,
    CareGbNursingAction,
    DigitalEmployeeSkills,
    AppUser,
    AppUserDetail,
    CareScheduleResultOld,
    CareTimeSlotOld,
)

# 设置日志
logger = logging.getLogger(__name__)


class CareUtils:
    """照护工具类，处理新数据库表的操作"""

    @staticmethod
    def get_caregivers():
        """获取所有护理员

        从app_user表中获取system_type='care'的用户，
        然后与app_user_detail表关联获取详细信息

        Returns:
            护理员列表，每个护理员包含id、name等信息
        """
        try:
            # 查询system_type='care'的用户
            care_users = AppUser.query.filter_by(system_type='care').all()

            if not care_users:
                logger.warning("没有找到system_type='care'的用户")
                return []

            # 获取用户名列表
            user_names = [user.user_name for user in care_users]

            # 查询对应的用户详情
            user_details = AppUserDetail.query.filter(
                AppUserDetail.app_user_name.in_(user_names)
            ).all()

            # 将用户和详情关联起来
            caregivers = []
            for user in care_users:
                # 查找对应的详情
                detail = next(
                    (d for d in user_details if d.app_user_name == user.user_name),
                    None
                )

                if detail:
                    # 构建护理员信息
                    caregiver = {
                        'id': user.user_id,
                        'user_name': user.user_name,
                        'name': detail.name or user.nick_name or user.user_name,
                        'skills': detail.skill or '',
                    }
                    caregivers.append(caregiver)

            logger.info(f"找到 {len(caregivers)} 名护理员")
            return caregivers

        except Exception as e:
            logger.error(f"获取护理员时出错: {str(e)}")
            return []

    @staticmethod
    def get_activity_name_by_nursing_id(nursing_id):
        """根据nursing_id获取活动名称

        从digital_employee_skills表中查找对应的活动名称

        Args:
            nursing_id: 护理ID，可能是单个ID或逗号分隔的多个ID

        Returns:
            活动名称，如果找不到则返回"老年人照护活动"
        """
        try:
            # 处理特殊情况
            if not nursing_id:
                logger.warning("nursing_id为空")
                return "老年人照护活动"

            # 将nursing_id拆分为列表
            nursing_ids = [id.strip() for id in str(nursing_id).split(',') if id.strip()]

            if not nursing_ids:
                logger.warning("解析后的nursing_id列表为空")
                return "老年人照护活动"

            # 依次尝试每个ID
            for id in nursing_ids:
                try:
                    # 尝试将ID转换为整数
                    skill = DigitalEmployeeSkills.query.filter_by(id=int(id)).first()
                    if skill and skill.name:
                        # 如果活动名称的第一个字符是数字，就将其去掉
                        activity_name = skill.name
                        if activity_name and len(activity_name) > 0 and activity_name[0].isdigit():
                            activity_name = activity_name[1:].strip()
                            logger.info(f"去掉活动名称前面的数字，原名称: {skill.name}, 新名称: {activity_name}")
                        return activity_name
                except (ValueError, TypeError):
                    logger.warning(f"无效的nursing_id: {id}")
                    continue

            # 如果所有ID都没有找到匹配项，返回默认名称
            logger.warning(f"没有找到匹配的活动名称，nursing_id: {nursing_id}")
            return "老年人照护活动"

        except Exception as e:
            logger.error(f"获取活动名称时出错: {str(e)}")
            return "老年人照护活动"

    @staticmethod
    def get_elder_actions(elder_id):
        """获取老人的护理动作

        从care_elder_demand表中获取老人的actions，
        然后与care_gb_nursing_action表关联获取nursing_id

        Args:
            elder_id: 老人ID

        Returns:
            护理动作列表，每个动作包含id、name、nursing_id等信息
        """
        try:
            # 查询老人的护理需求
            elder_demands = CareElderDemand.query.filter_by(
                elder=elder_id, arrange="1"
            ).all()

            if not elder_demands:
                logger.warning(f"老人 {elder_id} 没有护理需求记录")
                return []

            # 解析护理动作ID
            action_ids = []
            for demand in elder_demands:
                if demand.actions:
                    action_ids.extend([
                        int(action_id.strip())
                        for action_id in demand.actions.split(',')
                        if action_id.strip().isdigit()
                    ])

            if not action_ids:
                logger.warning(f"老人 {elder_id} 的护理动作为空")
                return []

            # 查询护理动作详情
            actions = CareGbNursingAction.query.filter(
                CareGbNursingAction.id.in_(action_ids)
            ).all()

            if not actions:
                logger.warning(f"老人 {elder_id} 的护理动作在数据库中不存在")
                return []

            # 构建护理动作列表
            elder_actions = []
            for action in actions:
                elder_actions.append({
                    'id': action.id,
                    'name': action.name,
                    'level': action.level,
                    'nursing_id': action.nursing_id,
                    'activity_name': CareUtils.get_activity_name_by_nursing_id(action.nursing_id)
                })

            logger.info(f"老人 {elder_id} 有 {len(elder_actions)} 个护理动作")
            return elder_actions

        except Exception as e:
            logger.error(f"获取老人护理动作时出错: {str(e)}")
            return []

    @staticmethod
    def match_caregiver_for_action(caregivers, action):
        """为护理动作匹配合适的护理员

        根据护理动作的nursing_id匹配具有相应技能的护理员

        Args:
            caregivers: 护理员列表
            action: 护理动作信息

        Returns:
            匹配的护理员，如果没有匹配则随机选择一个
        """
        try:
            if not caregivers:
                logger.warning("护理员列表为空")
                return None

            # 如果动作信息不完整或者是默认的"老年人照护活动"，随机选择护理员
            if not action or 'nursing_id' not in action or (
                action.get('activity_name') == "老年人照护活动" and
                action.get('name') == "老年人照护活动"
            ):
                logger.warning(f"护理动作信息不完整或是默认活动，随机选择护理员")
                return random.choice(caregivers)

            # 将nursing_id拆分为列表
            nursing_ids = []
            if action['nursing_id']:
                nursing_ids = [
                    id.strip()
                    for id in str(action['nursing_id']).split(',')
                    if id.strip()
                ]

            # 如果没有nursing_id，随机选择护理员
            if not nursing_ids:
                logger.warning(f"护理动作 {action.get('id')} 没有nursing_id，随机选择护理员")
                return random.choice(caregivers)

            # 匹配护理员
            matched_caregivers = []
            for caregiver in caregivers:
                # 解析护理员技能
                caregiver_skills = []
                if caregiver.get('skills'):
                    caregiver_skills = [
                        skill.strip()
                        for skill in str(caregiver['skills']).split(',')
                        if skill.strip()
                    ]

                # 检查是否有匹配的技能
                for nursing_id in nursing_ids:
                    if nursing_id in caregiver_skills:
                        matched_caregivers.append(caregiver)
                        break

            # 如果有匹配的护理员，随机选择一个
            if matched_caregivers:
                logger.info(f"为护理动作 {action.get('id')} 找到 {len(matched_caregivers)} 个匹配的护理员")
                return random.choice(matched_caregivers)

            # 如果没有匹配的护理员，随机选择一个
            logger.warning(f"没有找到匹配的护理员，随机选择一个")
            return random.choice(caregivers)

        except Exception as e:
            logger.error(f"匹配护理员时出错: {str(e)}")
            if caregivers:
                return random.choice(caregivers)
            return None
